package cloud.maque.base.dingding.hander;

import cloud.maque.base.dingding.service.DingdingTokenService;
import cloud.maque.framework.conf.PlatformConfigProperties;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * 对接口获取的再封装,不同的Token权限不一样
 * 数据存到Redis
 *
 * @author zhuyf
 * @date 2023/3/3 11:56
 */
@Component
public class DingdingTokenServiceHander {

    private static String DINGDING_REDIS_KEY = "dingding";

    private static long TIME_OUT = 7100;

    @Autowired
    DingdingTokenService tokenService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PlatformConfigProperties platformConfigProperties;

    /**
     * 获取企业内部的Token
     *
     * @return
     */
    public String GetAccessEnterpriseToken() {
        return GetAccessEnterpriseToken(platformConfigProperties.getDingding().getAppKey(), platformConfigProperties.getDingding().getAppSecret());
    }

    public String GetAccessEnterpriseToken(String appKey, String appSecret) {

        Assert.notNull(appKey, "钉钉AppKey不能为空");

        String key = DINGDING_REDIS_KEY + ":enterprise:" + appKey;
        if (redisTemplate.hasKey(key)) {
            return redisTemplate.opsForValue().get(key).toString();
        }
        String accessToken = tokenService.GetAccessEnterpriseToken(appKey, appSecret);

        if (StrUtil.isEmptyIfStr(accessToken)) {
            throw new RuntimeException("生成Token为空");
        }

        redisTemplate.opsForValue().set(key, accessToken, TIME_OUT, TimeUnit.SECONDS);

        return accessToken;
    }


    /**
     * 用户accessToken
     *
     * @param authCode
     * @return
     */
    public String GetAccessUserToken(String authCode) {

        String key = DINGDING_REDIS_KEY + ":user:" + platformConfigProperties.getDingding().getAppKey();
        if (redisTemplate.hasKey(key)) {
            return redisTemplate.opsForValue().get(key).toString();
        }
        String accessToken = tokenService.GetAccessUserToken(authCode);
        redisTemplate.opsForValue().set(key, accessToken, TIME_OUT, TimeUnit.SECONDS);
        return accessToken;
    }
}
